package org.mwielocha.jxcube.ut;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Sash;

public class CustomSash {
  
  protected Composite parent, leftComposite, rightComposite;
  protected Sash sash;
  protected int limit = 140, percent = 50;
  protected FormData sashData;
  
  public CustomSash(Composite parent, Composite leftComposite, Composite rightComposite) {
    this.parent = parent;
    this.leftComposite = leftComposite;
    this.rightComposite = rightComposite;
    createControl();
  }
  
  public Composite getParent() {
    return parent;
  }
  
  public void setLimit(int limit) {
    this.limit = limit;
  }
  
  public void setPercent(int percent) {
    this.percent = percent;
  }
  
  protected void createControl() {
    sash = new Sash (parent, SWT.VERTICAL);
    
    FormData leftCompositeData = new FormData ();
    leftCompositeData.left = new FormAttachment (0, 0);
    leftCompositeData.right = new FormAttachment (sash, 0);
    leftCompositeData.top = new FormAttachment (0, 0);
    leftCompositeData.bottom = new FormAttachment (100, 0);
    leftComposite.setLayoutData (leftCompositeData);

    sashData = new FormData ();
    sashData.left = new FormAttachment (percent, 0);
    sashData.top = new FormAttachment (0, 0);
    sashData.bottom = new FormAttachment (100, 0);
    sash.setLayoutData (sashData);
    sash.addListener (SWT.Selection, new Listener () {
        public void handleEvent (Event e) {
          recalculateSashPosition(e.x);
        }
    });
    
    FormData rightCompositeData = new FormData ();
    rightCompositeData.left = new FormAttachment (sash, 0);
    rightCompositeData.right = new FormAttachment (100, 0);
    rightCompositeData.top = new FormAttachment (0, 0);
    rightCompositeData.bottom = new FormAttachment (100, 0);
    rightComposite.setLayoutData (rightCompositeData);
    recalculateSashPosition(limit);
  }
  
  protected void recalculateSashPosition(int x) {
    Rectangle sashRect = sash.getBounds ();
    Rectangle shellRect = parent.getClientArea ();
    int right = shellRect.width - sashRect.width - limit;
    x = Math.max (Math.min (x, right), limit);
    if (x != sashRect.x)  {
        sashData.left = new FormAttachment (0, x);
        parent.layout ();
    }
  }
}
